package lab_15.com.acme.bankapp.client;

import java.io.*;
import java.net.*;


public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	void run() {
		try {
			// 1. creating a socket to connect to the server
			requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			// 2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			// 3: Communicating with the server
			do {
				try {
					message = (String) in.readObject();
					System.out.println("server>" + message);
					
					sendMessage("add");
					message = (String) in.readObject();
					System.out.println("server>" + message);
					
					sendMessage("accounttype=c;balance=77.0;overdraftlimit=10.0;name=Maxim;gender=m;");
					message = (String) in.readObject();
					System.out.println("server>" + message);
					
					sendMessage("printbank");
					message = (String) in.readObject();
					System.out.println("server>" + message);
					
					sendMessage("exit");
					message = (String) in.readObject();
					System.out.println("server>" + message);
				} catch (ClassNotFoundException e) {
					System.err.println("data received in unknown format");
				}
			} while (!message.equals("Bye!"));
		} catch (UnknownHostException e) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4: Closing connection
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(final String args[]) {
		BankClient client = new BankClient();
		client.run();
	}

}
